package cn.com.miao.lynx.common.secure.model;

import cn.com.miao.lynx.common.core.constant.LoginType;
import cn.com.miao.lynx.service.system.entity.SysPermission;
import cn.com.miao.lynx.service.system.entity.SysRole;
import cn.com.miao.lynx.service.system.entity.SysUser;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import lombok.Getter;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.security.SocialUserDetails;

import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * SecurityUser
 *
 * @title: SecurityUser
 * @description:
 * @author: dengmiao
 * @create: 2019-12-31 16:29
 **/
@Getter
public class SecurityUser extends SysUser implements UserDetails, SocialUserDetails {

    private LoginType loginType;

    public SecurityUser(SysUser sysUser, LoginType loginType) {
        BeanUtils.copyProperties(sysUser, this);
        this.loginType = loginType;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 权限集合
        List<GrantedAuthority> authorityList = Lists.newArrayList();
        List<SysPermission> permissions = this.getPermissions();
        Set<SysRole> roles = this.getRoles();
        // 添加请求权限
        if (permissions != null && permissions.size() > 0) {
            permissions.forEach(permission -> {
                if (StrUtil.isNotBlank(permission.getPerms())) {
                    authorityList.add(new SimpleGrantedAuthority(permission.getPerms()));
                }
            });
        }
        // 添加角色
        if (roles != null && roles.size() > 0) {
            roles.forEach(role -> {
                if(StrUtil.isNotBlank(role.getRoleCode())){
                    authorityList.add(new SimpleGrantedAuthority(role.getRoleCode()));
                }
            });
        }
        return authorityList;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.getStatus() != null && this.getStatus() == 1;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.getStatus() != null && this.getStatus() == 1;
    }

    @Override
    public String getUserId() {
        return Optional.ofNullable(this).map(u -> String.valueOf(u.getId())).orElse("");
    }
}
